package com.sky.aspect;

import com.sky.anno.AutoFill;
import com.sky.constant.AutoFillConstant;
import com.sky.context.BaseContext;
import com.sky.enumeration.OperationType;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.time.LocalDateTime;

@Aspect
@Component
@Slf4j
public class AutoFillAspect {

    @Pointcut("execution(* com.sky.mapper.*.*(..)) && @annotation(com.sky.anno.AutoFill)")
    private void pt(){}

    @Before("pt()")
    public void autoFill(JoinPoint jp) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
        log.info("自动填充功能。。。。。");
        // categoryMapper.update(category)
        //如何判断是否是新增？
        //1.获取切入点方法上有没有autofill注解
        MethodSignature signature = (MethodSignature) jp.getSignature();
        // 2.获取方法上的注解
        AutoFill autoFill = signature.getMethod().getAnnotation(AutoFill.class);
        //3.获取注解的value值
        OperationType operationType = autoFill.value();

        //4.获取方法参数
        Object[] args = jp.getArgs();

        if(args==null || args.length==0){
            return;
        }

        Object object  = args[0];

        //准备赋值数据
        LocalDateTime now = LocalDateTime.now();
        Long empId = BaseContext.getCurrentId();

        if(operationType==OperationType.INSERT){
            //新增：填充四个字段
            Method setCreateTime = object.getClass().getMethod(AutoFillConstant.SET_CREATE_TIME, LocalDateTime.class);
            Method setUpdateTime = object.getClass().getMethod(AutoFillConstant.SET_UPDATE_TIME, LocalDateTime.class);
            Method setCreateUser = object.getClass().getMethod(AutoFillConstant.SET_CREATE_USER, Long.class);
            Method setUpdateUser = object.getClass().getMethod(AutoFillConstant.SET_UPDATE_USER, Long.class);

            setCreateTime.invoke(object,now);
            setUpdateTime.invoke(object,now);
            setCreateUser.invoke(object, empId);
            setUpdateUser.invoke(object, empId);

        }else {
            //修改：填充两个字段 object==category
            Method setUpdateTime = object.getClass().getMethod(AutoFillConstant.SET_UPDATE_TIME, LocalDateTime.class);
            Method setUpdateUser = object.getClass().getMethod(AutoFillConstant.SET_UPDATE_USER, Long.class);

            setUpdateTime.invoke(object,now);
            setUpdateUser.invoke(object, empId);
        }
    }


}
